package com.changyue.activity.home;

import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.changyue.activity.basic.BasicActivity;
import com.changyue.activity.me.IntroActivity;
import com.changyue.bleHelper.Req.BLEReq;
import com.changyue.bleHelper.Req.BLEStartReq;
import com.changyue.bleHelper.Req.BLEStopReq;
import com.changyue.bleHelper.ScanActivity;
import com.changyue.activity.me.SettingActivity;
import com.changyue.activity.me.SettingTempActivity;
import com.changyue.bleHelper.BLEDeviceConfig;
import com.changyue.blood.databinding.ActivityHomeBinding;
import com.changyue.ui.HeadView;
import com.changyue.util.CustomToast;
import com.changyue.util.EmptyUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.UUID;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.BleLog;
import cn.com.heaton.blelibrary.ble.callback.BleNotifyCallback;
import cn.com.heaton.blelibrary.ble.callback.BleReadCallback;
import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback;
import cn.com.heaton.blelibrary.ble.model.BleDevice;
import cn.com.heaton.blelibrary.ble.utils.ByteUtils;


public class HomeActivity extends BasicActivity {

    public static String TAG = HomeActivity.class.getName();

    private boolean isStart = false;

    private ActivityHomeBinding binding;

    private Ble<BleDevice> ble = Ble.getInstance();

    private InputCDHView inputCDHView;

    public static void start(Context context) {
        Intent intent = new Intent(context, HomeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();
        loadData();

        EventBus.getDefault().register(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedUpdate) {
            isNeedUpdate = false;
            loadData();
        }
    }

    @Subscribe
    public void onEventMainThread(String event) {
        if (event != null) {
            if (event.contains("Setting")) {
                isNeedUpdate = true;
            } else if (event.contains("Scan")) {
                isNeedUpdate = true;
            }
        }
    }

    public void initView() {
        binding.headView.setLeftVisibility(false);
        binding.headView.setRightTxt("设置");
        binding.headView.setRightTxtVisibility(true);
        binding.headView.setOnRightClickListener(new HeadView.OnRightClickListener() {
            @Override
            public void onRightClickListener(View view) {
                SettingActivity.start(HomeActivity.this);
            }
        });

        binding.ivSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ScanActivity.start(HomeActivity.this);
                inputCDHView = new InputCDHView(HomeActivity.this);
                inputCDHView.setCdhDialogInterface(new InputCDHDialogInterface() {
                    @Override
                    public void action(Boolean isOk, String cdh) {
                        inputCDHView = null;
                    }
                });
                inputCDHView.show();
            }
        });

        binding.ivInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntroActivity.start(HomeActivity.this);
            }
        });

        binding.btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isStart) {
                    isStart = true;
                    binding.btnStart.setText("结束");
                    sendBleRequest(new BLEStartReq());
                } else  {
                    isStart = false;
                    binding.btnStart.setText("开始");
                    sendBleRequest(new BLEStopReq());
                }
            }
        });
    }

    public void loadData() {
        binding.headView.setTitle(BLEDeviceConfig.getInstance().getTypeName());
//        binding.targetTemp.setText(BLEDeviceConfig.getInstance().getTargetTempUnit());
//        binding.bleName.setText(BLEConnector.getBLEName(ble));
    }

    public void sendBleRequest(BLEReq bleReq) {
        if (EmptyUtil.isEmpty(ble.getConnectedDevices())) {
            CustomToast.middleBottom(HomeActivity.this, "蓝牙断开连接");
            loadData();
            return;
        }

        BleDevice device = ble.getConnectedDevices().get(0);
        ble.write(device, bleReq.req, new BleWriteCallback<BleDevice>() {
            @Override
            public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic characteristic) {
                Log.e(TAG, "onWriteSuccess: ");
            }

            @Override
            public void onWriteFailed(BleDevice device, int failedCode) {
                Log.e(TAG, "onWiteFailed: " + failedCode);
            }

        });

        if (bleReq instanceof BLEStartReq) {
          ble.enableNotify(device, true, new BleNotifyCallback<BleDevice>() {
              @Override
              public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) {
                  UUID uuid = characteristic.getUuid();
                  BleLog.e(TAG, "onChanged==uuid:" + uuid.toString());
                  BleLog.e(TAG, "onChanged==data:" + ByteUtils.toHexString(characteristic.getValue()));
              }

              @Override
              public void onNotifySuccess(BleDevice device) {
                  super.onNotifySuccess(device);
                  BleLog.e(TAG, "onNotifySuccess");
              }

              @Override
              public void onNotifyFailed(BleDevice device, int failedCode) {
                  super.onNotifyFailed(device, failedCode);
                  BleLog.e(TAG, "onNotifyFailed " + failedCode);
              }

              @Override
              public void onNotifyCanceled(BleDevice device) {
                  super.onNotifyCanceled(device);
                  BleLog.e(TAG, "onNotifyCanceled");
              }
          });

          ble.read(device, new BleReadCallback<BleDevice>() {
              @Override
              public void onReadSuccess(BleDevice dedvice, BluetoothGattCharacteristic characteristic) {
                  super.onReadSuccess(dedvice, characteristic);
                  UUID uuid = characteristic.getUuid();
                  BleLog.e(TAG, "onChanged==uuid:" + uuid.toString());
                  BleLog.e(TAG, "onChanged==data:" + ByteUtils.toHexString(characteristic.getValue()));
              }

              @Override
              public void onReadFailed(BleDevice device, int failedCode) {
                  super.onReadFailed(device, failedCode);
                  BleLog.e(TAG, "onReadFailed " + failedCode);
              }
          });

        }

    }

}